package com.watchthelan.web.administrator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.watchthelan.domain.Administrator;
import com.watchthelan.domain.AdministratorPassword;
import com.watchthelan.service.administrator.AdministratorManager;

// TODO: This class is in very bad shape. Had no time to finish...
public class AdministratorPasswordEditFormController extends SimpleFormController {
protected final Log logger = LogFactory.getLog(getClass());
	
	private AdministratorManager administratorManager;
	
	public ModelAndView onSubmit(Object command)
	throws ServletException {
		AdministratorPassword administratorPassword = (AdministratorPassword) command;
		logger.info("administrator password: " + administratorPassword.toString());
		logger.info("get password");
		String administratorId = administratorPassword.getAdministratorId();
		logger.info("administrator id: " + administratorId);
		Administrator administrator = new Administrator();
		if (administratorId != null) {
			administrator = administratorManager.getAdministratorById(new Long(administratorId));
			administrator.setPassword(administratorPassword.getNewPassword());
			administratorManager.updateAdministrator(administrator);
			return new ModelAndView(new RedirectView("administrator.htm?id=" + administratorId));
		}
		return new ModelAndView(new RedirectView("administrators.htm"));
		
	}
	
	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
		String administratorId = request.getParameter("id");
		logger.info("administrator id: " + administratorId);
		AdministratorPassword administratorPassword = new AdministratorPassword();
		administratorPassword.setAdministratorId(administratorId);
		Administrator administrator = administratorManager.getAdministratorById(new Long(administratorId));
		administratorPassword.setOldPassword(administrator.getPassword());
		logger.info("administrator old password: " + administratorPassword.getOldPassword());
		return administratorPassword;
	}	

	public AdministratorManager getAdministratorManager() {
		return administratorManager;
	}

	public void setAdministratorManager(AdministratorManager administratorManager) {
		this.administratorManager = administratorManager;
	}
}
